/**
 * Funf: Open Sensing Framework
 * Copyright (C) 2010-2011 Nadav Aharony, Wei Pan, Alex Pentland. 
 * Acknowledgments: Alan Gardner
 * Contact: nadav@media.mit.edu
 * 
 * This file is part of Funf.
 * 
 * Funf is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as 
 * published by the Free Software Foundation, either version 3 of 
 * the License, or (at your option) any later version. 
 * 
 * Funf is distributed in the hope that it will be useful, but 
 * WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public 
 * License along with Funf. If not, see <http://www.gnu.org/licenses/>.
 */
package edu.mit.media.funf.storage;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

/**
 * Simple database service that is able to write timestamp, name, value tuples.
 * 
 * This class can be subclassed to provide custom implementations of Archive and 
 * SQliteHelper.Subclasses have no access to data queue.
 * @author alangardner
 *
 */
public abstract class DatabaseService extends StorageService {
  private static final String TAG = DatabaseService.class.getSimpleName();
  
	private Map<String, SQLiteOpenHelper> databaseHelpers = null; // Cache open database helpers
		
	/**
	 * Returns the file archive for the database.
	 * @param databaseName
	 * @return
	 */
	public Archive<File> getArchive(String databaseName) {
		return DefaultArchive.getArchive(this, databaseName);
	}
	
  private SQLiteOpenHelper getOrCreateDatabaseHelper(String databaseName) {
    if (databaseHelpers == null) {
      databaseHelpers = new HashMap<String, SQLiteOpenHelper>();
    }
    SQLiteOpenHelper dbHelper = databaseHelpers.get(databaseName);
    if (dbHelper == null) {
      Log.i(TAG, "DataBaseService: Creating database '" + databaseName + "'");
      dbHelper = getDatabaseHelper(databaseName);
      databaseHelpers.put(databaseName, dbHelper);
    }
    return dbHelper;
  }
	
  @Override
  public void onDestroy() {
    super.onDestroy();
    
    if (databaseHelpers != null) {
      for (SQLiteOpenHelper dbHelper : databaseHelpers.values()) {
        dbHelper.close();
      }
    }
    
    Log.i(TAG, "Destroyed");
  }
	
	/**
	 * The NameValueDatabaseHelper
	 * @param name
	 * @return
	 */
	protected abstract SQLiteOpenHelper getDatabaseHelper(String name);
	
	/**
	 * Pulls data from the intent to update the database.  This method is called from within a transaction.
	 * Throw a SQLException to signify a failure and rollback the transaction.
	 * @param db
	 * @param intent
	 */
	protected abstract void updateDatabase(SQLiteDatabase db, Intent intent) throws SQLException;
	
	protected void archiveStoredData(String storageName) {
	  runArchive(storageName);
	}
	
	protected void runArchive(String storageName) {
		SQLiteOpenHelper dbHelper = getOrCreateDatabaseHelper(storageName);
		SQLiteDatabase db = null;
		File dbFile = null;
		try{ 
		  db = dbHelper.getReadableDatabase();
		  dbFile = new File(db.getPath());
		}
		catch(Exception e){
		  Log.e(TAG, "DataBaseService: archive error",e);
		}
		finally{
		  if(db != null)
		    db.close();
		  dbHelper.close();
		}
		
		if(dbFile != null){
      Log.i(TAG, "Running archive: " + dbFile.getAbsolutePath());
  		Archive<File> archive = getArchive(storageName);
  		if (archive.add(dbFile)) {
  			dbFile.delete();
  		}
		}
	}
	
	
	
	protected void storeIntentData(String storageName, Intent intent) {
	  writeToDatabase(storageName, intent);
	}
	
	/**
	 * Write data to the database in a transaction
	 * NOTE: Should only be called by one thread at a time (the writeThread)
	 * @param datum
	 */
	protected void writeToDatabase(String storageName, Intent intent) {
		Log.i(TAG, "Writing to database: " + storageName);
		SQLiteOpenHelper dbHelper = getOrCreateDatabaseHelper(storageName);
		SQLiteDatabase db = null;
		try {
		  db = dbHelper.getWritableDatabase();
			db.beginTransaction();
			updateDatabase(db, intent);
			db.setTransactionSuccessful();
			Log.i(TAG, "Writing successful");
		} catch (Exception e) {
			Log.e(TAG, "DataBaseService: save error",e);
		} finally {
		  if(db != null){
		    db.endTransaction();
		    db.close();
		  }
		  dbHelper.close();
		}
	}

	private final IBinder mBinder = new Binder(){
    public DatabaseService getService() {
      return DatabaseService.this;
    }
  };
  
	public IBinder onBind(Intent intent) {
	  return mBinder;
	}
}
